﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

/// <summary>
/// 数据库改造备用
/// </summary>
class SqlHelper
{
    public static string dboname;
    private static string connStr;
    public static string ConnStr
    {
        get
        {
            return connStr = "server=127.0.0.1;database="+ dboname + ";uid=sa;pwd=root";
        }
        set
        {
            connStr = value;
        }
    }

    //string constr = "server=.;database=myschool;integrated security=SSPI";
    //string constr = "server=.;database=myschool;uid=sa;pwd=sa";
    //string constr = "data source=.;initial catalog=myschool;user id=sa;pwd=sa";


    //直接用可变长度参数的方式写一个完整的SqlHelper

    /// <summary>
    /// 增删改
    /// </summary>
    /// <param name="sql"></param>
    /// <param name="parameters"></param>
    /// <returns></returns>
    public static int ExecuteNonQuery(string sql, params SqlParameter[] parameters)
    {
        using (SqlConnection conn = new SqlConnection(ConnStr))
        {
            conn.Open();
            using (SqlCommand cmd = conn.CreateCommand())
            {
                cmd.CommandText = sql;
                cmd.Parameters.AddRange(parameters);
                return cmd.ExecuteNonQuery();
            }
        }
    }
    /// <summary>
    /// 查
    /// </summary>
    /// <param name="sql"></param>
    /// <param name="parameters"></param>
    /// <returns></returns>
    public static object ExecuteScalar(string sql, params SqlParameter[] parameters)
    {
        
        try
        {
            using (SqlConnection conn = new SqlConnection(ConnStr))
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = sql;
                    cmd.Parameters.AddRange(parameters);
                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                    DataSet data = new DataSet();
                    adapter.Fill(data);
                    return data;
                }
            }
        }
        catch (Exception e)
        {
            UnityEngine.Debug.Log(sql+"============="+e);
        }
        return null;
        
    }

}
